﻿
window.Foresight = window.Foresight || {};
(function(ns) {
    ns.Util = {};
    ns.Util.JsonResponseCode = {
        UNAUTHORIZED: -100,
        UNROOMCONNECTED: -101,
        SUCCEED: 0
    };

    ns.Util.api_ajax = function(options) {
        // console.log(JSON.stringify(options));
        var post_form = options.data;
        var opt = null;
        var timeout = 30;
        if (options.needcloselaunch) {
            timeout = 5;
        }
        if (/post/ig.test(options.type)) {
            opt = {
                url: options.url,
                method: options.type,
                cache: false,
                timeout: timeout,
                dataType: 'json',
                data: {
                    values: post_form,
                    files: options.files || {}
                }
            };
        } else {
            var arr = [];
            for (var key in post_form) {
                arr.push(key + '=' + encodeURIComponent(post_form[key]));
            }
            if (arr.length) {
                if (!/\?/.test(options.url)) {
                    options.url = options.url + '?' + arr.join('&');
                } else {
                    if (/[\?\&]$/.test(url)) {
                        options.url = options.url + arr.join('&');
                    } else {
                        options.url = options.url + '&' + arr.join('&');
                    }
                }
            }
            opt = {
                url: options.url,
                method: 'get',
                cache: true,
                timeout: timeout,
                dataType: 'json'
            };
        }
        var auiToast = null;
        if (options.toast) {
            try {
                auiToast = new auiToast();
            } catch (e) {}
            if (auiToast) {
                options.toastmsg = options.toastmsg || '加载中';
                auiToast.loading({
                    title: options.toastmsg,
                    duration: 2000
                }, function(ret) {});
            }
        }
        api.ajax(opt, function(ret, err) {
            // console.log(JSON.stringify(opt));
            // console.log(JSON.stringify(ret));
            // console.log(JSON.stringify(err));
            if (options.toast && auiToast) {
                auiToast.hide();
            }
            if (ret) {
                data = ret;
                if (data == undefined || data == null) {
                    try {
                        console.error(options.url);
                    } catch (e) {}
                    throw new Error("Ajax response null.");
                } else if (typeof data.Code == "undefined") {
                    try {
                        console.error(data);
                    } catch (e) {}
                    throw new Error("Incorrect json data.");
                }
                if (data.Code == ns.Util.JsonResponseCode.UNAUTHORIZED) {
                    try {
                        ns.Util.removePrefs('uid');
                        ns.Util.removePrefs('HeadImg');
                        ns.Util.removePrefs('username');
                    } catch (e) {}
                    ns.Util.open_login(options);
                } else if (data.Code == ns.Util.JsonResponseCode.UNROOMCONNECTED) {
                    ns.Util.open_roomconnect(options);
                } else if (data.Code == ns.Util.JsonResponseCode.SUCCEED) {
                    if (typeof options.success == "function")
                        options.success.call(this, data.Result, null); //调用指定的成功处理函数
                } else if (data.Code < 0) {
                    if (typeof options.error == 'function')
                        options.error.call(this, data.Error, null); //调用指定的错误处理函数
                } else {
                    throw new Error("Unknown json code: " + data.Code + ".");
                }
            } else {
                if (options.needcloselaunch) {
                    options.success.call(this, null, null);
                    return;
                }
                if (err.code == 0) {
                    if (api.toast) {
                        // api.toast({
                        //     msg: '当前服务不可用，请稍后再试',
                        //     duration: 5000,
                        //     location: 'bottom'
                        // });
                    }
                } else if (err.code == 1) {
                    if (api.toast) {
                        api.toast({
                            msg: '连接服务器超时',
                            duration: 5000,
                            location: 'bottom'
                        });
                    }
                } else if (err.code == 2) {
                    if (api.toast) {
                        api.toast({
                            msg: '授权错误',
                            duration: 2000,
                            location: 'bottom'
                        });
                    }
                } else if (err.code == 3) {
                    if (api.toast) {
                        api.toast({
                            msg: '数据类型错误',
                            duration: 2000,
                            location: 'bottom'
                        });
                    }
                }

                if (typeof options.error == 'function') {
                    options.error.call(this, '', null);
                }
            }
        });
    }
    ns.Util.ajax = function(options) {
        options.url = CONFIG.apiurl;
        options.data = ns.Util.extend(options.data, {
            device: api.deviceId,
        });
        var uid = api.getPrefs({
            sync: true,
            key: 'uid'
        });
        if (uid) {
            options.data = ns.Util.extend(options.data, {
                uid: uid
            });
        }
        var xiaoquid = api.getPrefs({
            sync: true,
            key: 'my_chosen_xiaoquid'
        });
        if (xiaoquid) {
            options.data = ns.Util.extend(options.data, {
                xiaoquid: xiaoquid
            });
        }
        var needlogin = true;
        var needroom = false;
        for (var i = 0; i < POSTACTION.length; i++) {
            if (POSTACTION[i].action == options.data.action && POSTACTION[i].extlogin) {
                needlogin = false;
            }
            if (POSTACTION[i].action == options.data.action && POSTACTION[i].incroom) {
                needroom = true;
            }
        }
        options.data = ns.Util.extend(options.data, {
            needlogin: needlogin,
            needroom: needroom
        });
        ns.Util.api_ajax(options);
    };
    ns.Util.extend = function(o, n) {
        for (var p in n) {
            if (n.hasOwnProperty(p) && (!o.hasOwnProperty(p)))
                o[p] = n[p];
        }
        return o;
    };
    ns.Util.post = function(data, callback, options) {
        if (!options) {
            options = {};
        }
        return ns.Util.ajax(ns.Util.extend(options, {
            cache: false,
            success: function(result, textStatus) {
                if (typeof callback == "function") callback(true, result, null);
            },
            error: function(err, textStatus) {
                if (typeof callback == "function") callback(false, null, err);
            },
            url: (options && options.url) || '',
            data: data,
            type: 'POST'
        }));
    };
    //callback: funtion(succeed,data,error){};
    ns.Util.get = function(data, callback, options) {
        if (!options) {
            options = {};
        }
        return ns.Util.ajax(ns.Util.extend(options, {
            cache: false,
            success: function(result, textStatus) {
                if (typeof callback == "function") callback(true, result, null);
            },
            error: function(err, textStatus) {
                if (typeof callback == "function") callback(false, null, err);
            },
            url: (options && options.url) || '',
            data: data,
            type: 'GET'
        }));
    };
    ns.Util.open_roomconnect = function(options) {
        var that = this;
        var ismain = (options && options.ismain) || false;
        api.confirm({
            title: '提示',
            msg: '以下内容仅对认证业主用户开放，是否前往认证?',
            buttons: ['是', '否']
        }, function(ret, err) {
            if (ret.buttonIndex == 1) {
                ns.Util.openWinDirect('dl_myxiaoqu_frm', '小区认证', null, {
                    ismain: ismain
                });
            }
        });
    }
    ns.Util.open_login = function(options) {
        var that = this;
        var ismain = (options && options.ismain) || false;
        ns.Util.openWinDirect('dl_login_frm', '登录', null, {
            ismain: ismain
        });
    }
    ns.Util.openWin = function(name, title, pageParam, options) {
        if (PAGE.INCROOM.indexOf(name) > -1) {
            var ismain = (options && options.ismain) || false;
            ns.Util.post({
                action: 'checkconnectroom'
            }, function(succeed, data, err) {
                if (succeed) {
                    ns.Util.openWinDirect(name, title, pageParam, options);
                } else if (err) {
                    ns.Util.open_roomconnect(options);
                }
            }, {
                ismain: ismain
            });
            return;
        }
        if (PAGE.EXTLOGIN.indexOf(name) == -1) {
            var ismain = (options && options.ismain) || false;
            ns.Util.post({
                action: 'checkloginstatus'
            }, function(succeed, data, err) {
                if (succeed) {
                    ns.Util.openWinDirect(name, title, pageParam, options);
                } else if (err) {
                    ns.Util.open_login(options);
                }
            }, {
                ismain: ismain
            });
            return;
        }
        ns.Util.openWinDirect(name, title, pageParam, options);
    }
    ns.Util.openWinDirect = function(name, title, pageParam, options) {
        if (!pageParam || pageParam == null) {
            pageParam = {
                title: title,
                url: name + '.html'
            };
        }
        if (!pageParam.title) {
            pageParam.title = title;
        }
        if (!pageParam.url) {
            pageParam.url = name + '.html'
            if (name == 'dl_shop_frm' || name == 'dl_product_frm') {
                name = name + '_' + pageParam.id;
            }
        }
        var delay = 0;
        if (api.systemType != 'ios') {
            delay = 100;
        }
        var url = '../frame.html';
        if (options && options.ismain) {
            url = 'frame.html';
        }
        api.openTabLayout({
            hideNavigationBar: true,
            hideTabBar: true,
            useWKWebView: true,
            name: name,
            url: url,
            delay: delay,
            slidBackEnabled: false,
            vScrollBarEnabled: false,
            pageParam: pageParam,
            reload: true,
            rect: {
                x: 0,
                y: 0,
                w: 'auto',
                h: 'auto'
            }
        });
    }
    ns.Util.getPrefsVaue = function(key) {
        var value = api.getPrefs({
            sync: true,
            key: key
        });
        return value;
    }
    ns.Util.removePrefs = function(key) {
        api.removePrefs({
            key: key
        });
    }
    ns.Util.getQueryString = function(name, url) {
        url = url || window.location.search;
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = url.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    }
    ns.Util.check_mobile = function(phonenumber) {
        if (!(/^1[3456789]\d{9}$/.test(phonenumber))) {
            return false;
        }
        return true;
    }
    ns.Util.parseDateTime = function(dtString, dateformat) {
        if (!isNaN(dtString)) {
            return new Date(dtString - 0);
        }
        if (!dtString) {
            throw "Invalid dtString for ParseDateTime.";
        }
        //for JavaScriptSerializer.Serialize
        if (/\/Date\((\-?\d+)\)\//.test(dtString)) {
            return new Date(dtString.replace(/\/Date\((\-?\d+)\)\//, "$1") - 0);
        }
        dateformat = dateformat || "yyyy-MM-dd";
        //"2012-10-24 12:11:10.999".match(reg)
        //["2012-10-24 12:11:10.999", "2012", "10", "24", " 12:11:10.999", "12", "11", "10", ".999", "999"]
        var reg = /(\d+)[\/\-](\d+)[\/\-](\d+)( (\d+)\:(\d+)\:(\d+)(\.(\d+))*)*/;
        var m = dtString.match(reg);
        if (m) {
            var dt = null;
            var year, month, date;
            if (/[y]+[\/\-][m]+[\/\-][d]+/i.test(dateformat)) { /* yyyy-MM-dd */
                year = m[1];
                month = m[2];
                date = m[3];
            } else if (/[m]+[\/\-][d]+[\/\-][y]+/i.test(dateformat)) { /* MM/dd/yyyy */
                year = m[3];
                month = m[1];
                date = m[2];
            } else if (/[d]+[\/\-][m]+[\/\-][y]+/i.test(dateformat)) { /* dd/MM/yyyy */
                year = m[3];
                month = m[2];
                date = m[1];
            } else {
                throw "Invalid dateformat for ParseDateTime.";
            }
            if (year && month < 13 && date < 32) {
                dt = new Date(year - 0, month - 1, date - 0);
            } else {
                throw "Invalid dtString for ParseDateTime.";
            }
            if (dt) {
                if (m[4]) {
                    dt.setHours(m[5] - 0);
                    dt.setMinutes(m[6] - 0);
                    dt.setSeconds(m[7] - 0);
                }
                if (m[8]) {
                    dt.setMilliseconds(m[9].replace(/^(\d{1,3})(\d*)/, "$1") - 0);
                }
            }
            return dt;
        }
        throw "Invalid dtString for ParseDateTime.";
    }
    ns.Util.DateFormat = function(time, fmt) {
        if (!time) {
            return '';
        }
        var o = {
            "M+": time.getMonth() + 1, //月份
            "d+": time.getDate(), //日
            "h+": time.getHours(), //小时
            "m+": time.getMinutes(), //分
            "s+": time.getSeconds(), //秒
            "q+": Math.floor((time.getMonth() + 3) / 3), //季度
            "S": time.getMilliseconds() //毫秒
        };
        if (/(y+)/.test(fmt))
            fmt = fmt.replace(RegExp.$1, (time.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o) {
            if (new RegExp("(" + k + ")").test(fmt)) {
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            }
        }
        return fmt;
    };
    ns.Util.toast = function(err) {
        api.toast({
            msg: err,
            duration: 2000,
            location: 'bottom'
        });
    }
    ns.Util.confirmPer = function(perm, callback) {
        var has = ns.Util.hasPermission(perm);
        var permName=perm;//无权限的名称
        var granted = true;
        if (has && has.length > 0) {
            for (var i = 0; i < has.length; i++) {
                if (!has[i].granted) {
                    granted = false;
                    permName=has[i].name;
                }
            }
        }
        if (!granted) {
            api.confirm({
                title: '提醒',
                msg: '没有获得 ' + permName + " 权限\n是否前往设置？",
                buttons: ['去设置', '取消']
            }, function(ret, err) {
                if (1 == ret.buttonIndex) {
                    ns.Util.reqPermission(perm, callback);
                }
            });
            return false;
        }
        if (callback) {
            callback();
        }
        return true;
    };
    ns.Util.hasPermission = function(one_per) {
        if (!one_per) {
            return;
        }
        var perms = new Array();
        perms.push(one_per);
        perms.push('storage');
        //IOS 使用相机功能时，需添加photos 相册权限判断
        if(one_per=='camera'){
            perms.push('photos'); 
        } 
        var rets = api.hasPermission({
            list: perms
        });
        return rets;
    };
    ns.Util.reqPermission = function(one_per, callback) {
        var perms = new Array();
        perms.push(one_per);
        perms.push('storage');
        //IOS 使用相机功能时，需添加photos 相册权限判断
        if(one_per=='camera'){
            perms.push('photos'); 
        } 
        api.requestPermission({
            list: perms,
            code: 100001
        }, function(ret, err) {
            if (callback) {
                var list = ret.list;
                if (list && list.length > 0) {
                    var granted = true;
                    for (var i = 0; i < list.length; i++) {
                        if (!list[i].granted) {
                            granted = false;
                        }
                    }
                    if (granted) {
                        callback();
                    }
                }
                return;
            }
            var str = '请求结果：\n';
            str += '请求码: ' + ret.code + '\n';
            str += "是否勾选\"不再询问\"按钮: " + (ret.never ? '是' : '否') + '\n';
            str += '请求结果: \n';
            var list = ret.list;
            for (var i in list) {
                str += list[i].name + '=' + list[i].granted + '\n';
            }
        });
    }
})(window.Foresight);
